package com.cw.jeeyt.service.impl.process;

import java.util.ArrayList;
import java.util.List;

import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.idm.api.User;
import org.flowable.idm.engine.impl.UserQueryImpl;
import org.flowable.idm.engine.impl.persistence.entity.UserEntity;
import org.flowable.idm.engine.impl.persistence.entity.UserEntityImpl;

import com.cw.jeeyt.common.StringUtils;
import com.cw.jeeyt.common.utils.SpringContextHolder;
import com.cw.jeeyt.dao.intf.security.SecurityUserDao;
import com.cw.jeeyt.dao.model.security.SecurityUserDo;

/**
 * 扩展Flowable用户Service
 *
 * @author liuruijun
 * @version 2018-08-02
 */
public class FlowUserQueryImpl extends UserQueryImpl {

    private static final long serialVersionUID = 1L;

    private SecurityUserDao userDao;

    public static UserEntity toFlowableUser(SecurityUserDo user) {
        if (user == null) {
            return null;
        }
        UserEntity userEntity = new UserEntityImpl();
        userEntity.setId(user.getUsername());
        userEntity.setFirstName(user.getUsername());
        userEntity.setLastName(StringUtils.EMPTY);
        userEntity.setPassword(user.getPassword());
        userEntity.setEmail(user.getEmail());
        userEntity.setRevision(1);
        return userEntity;
    }

    public SecurityUserDao getUserDao() {
        if (userDao == null) {
            userDao = SpringContextHolder.getBean(SecurityUserDao.class);
        }
        return userDao;
    }

    @Override
    public long executeCount(CommandContext commandContext) {
        return executeQuery().size();
    }

    @Override
    public List<User> executeList(CommandContext commandContext) {
        return executeQuery();
    }

    protected List<User> executeQuery() {
        if (getId() != null) {
            List<User> result = new ArrayList<>();
            result.add(findById(getId()));
            return result;

        } else if (getIdIgnoreCase() != null) {
            List<User> result = new ArrayList<>();
            result.add(findById(getIdIgnoreCase()));
            return result;

        } else {
            return executeAllUserQuery();
        }
    }

    protected List<User> executeNameQuery(String name) {
        String fullName = name.replaceAll("%", "");
        return executeUsersQuery(fullName);
    }

    protected List<User> executeAllUserQuery() {
        return executeUsersQuery("");
    }

    protected UserEntity findById(String userId) {

        SecurityUserDo user = getUserDao().getUserByUserId(userId);
        return toFlowableUser(user);
    }

    protected List<User> executeUsersQuery(String fullName) {

        return new ArrayList<>();
    }

}
